package com.mofeng.myshop.until;

import com.mofeng.myshop.until.rcon.Rcon;
import org.rosuda.REngine.Rserve.RConnection;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 调用R语言的客户端连接池，提供R语言RConnection客户端的统一管理
 */
public class RconPoolUtil {
    //地址
    private static String host;

    //端口
    private static int port;

    //密码
    private static String password;

    //最大连接数
    private static int maxConnection;

    //等待超时时间（单位毫秒）
    private static int waitTimeout;

    //存放活跃的连接（正处于使用的连接）
    private static final LinkedBlockingQueue<RConnection> busy = new LinkedBlockingQueue<>();

    //空闲的连接
    private static final LinkedBlockingQueue<RConnection> idle = new LinkedBlockingQueue<>();

    //已创建的连接数
    private static final AtomicInteger createCount = new AtomicInteger(0);

    @Value("${Rserve.RConnection.host:127.0.0.1}")
    public void setHost(String host) {
        RconPoolUtil.host = host;
    }

    @Value("${Rserve.RConnection.port:6311}")
    public void setPort(int port) {
        RconPoolUtil.port = port;
    }

    @Value("${Rserve.RConnection.password:conan}")
    public void setPassword(String password) {
        RconPoolUtil.password = password;
    }

    @Value("${RConnection.maxConnection:10}")
    public void setMaxConnection(int maxConnection) {
        RconPoolUtil.maxConnection = maxConnection;
    }

    @Value("${RConnection.waitTimeout:1500}")
    public void setWaitTimeout(int waitTimeout) {
        RconPoolUtil.waitTimeout = waitTimeout;
    }

    public static void main(String[] args) {
        try {
            Rcon rcon = new Rcon(host, port, password);

            // 发送命令并获取响应
//            String com = "GiveItem 76561198096604961 Blueprint'/Game/PrimalEarth/CoreBlueprints/Weapons/PrimalItemAmmo_AdvancedBullet.PrimalItemAmmo_AdvancedBullet' 100 0 0";
            String com = "SpawnDino 76561198096604961 Blueprint'/Game/PrimalEarth/Dinos/Achatina/Achatina_Character_BP.Achatina_Character_BP' 1 1 0 0 0";
            String response = rcon.command(com);

            // 处理响应，可以根据需要进行逻辑处理
            System.out.println(response);
            rcon.disconnect();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }



    public void sendRconCommand(String command) {
        RconPoolUtil.host = "111.197.179.99";
//        RConnectionPoolUtil.port = 27034;
        RconPoolUtil.port = 32330;
        RconPoolUtil.password = "test1";
        try {
            Rcon rcon = new Rcon(host, port, password);

            // 发送命令并获取响应
//            String response = rcon.command(command);

            // 处理响应，可以根据需要进行逻辑处理

            rcon.disconnect();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
